import 'package:flutter/material.dart';
import 'package:flutter_application_cyber/net/cn_net_helper.dart';
import 'package:flutter_application_cyber/model/cn_net_response.dart';
import 'package:flutter_application_cyber/pages/Mate/cn_mateIng_page.dart';
import 'package:flutter_application_cyber/pages/Mine/cn_coinStore_Page.dart';
import 'package:provider/provider.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'dart:convert';
import 'Models/cn_CountryModel.dart';
import 'Models/cn_CountryListModel.dart';
import 'package:flutter_application_cyber/tools/cn_app_popView.dart';
import 'package:flutter_util_code/toast_utils.dart';
import 'package:flutter_application_cyber/pages/Mate/Models/cn_channel_model.dart';
import 'package:flutter_application_cyber/pages/Mate/cn_calling_page.dart';
import 'package:flutter_application_cyber/pages/Mate/Models/cn_AnchorViewModel.dart';
import 'package:flutter_application_cyber/tools/cn_event_bus.dart';
import 'package:svgaplayer_flutter/svgaplayer_flutter.dart';
import 'package:flutter_application_cyber/tools/cn_event_busUtils.dart';
import 'dart:async';
import '../../tools/cn_click_utils.dart';

class CnMateCnHomePage extends StatefulWidget {
  const CnMateCnHomePage({Key? key}) : super(key: key);

  @override
  State<CnMateCnHomePage> createState() => _CnHomePagePageState();
}

class _CnHomePagePageState extends State<CnMateCnHomePage> {
  List<CnCountryModel> countryDataList = [];
  String priceNumber = 'Free';
  String country = 'Global';
  int availableCoins = 0;
  UserInfoModel getUserInfo() {
    return Provider.of<ChangeUserInfoModel>(context, listen: false).info;
  }

  StreamSubscription? event;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('images/mate_bg_page.png'),
          fit: BoxFit.fill,
        ),
      ),
      child: SafeArea(
          child: Column(
        children: [
          Container(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                InkWell(
                  onTap: () {
                    if (!CnClickUtils.isClick()) return;

                    _showCustomDialog(context, countryDataList,
                        (CnCountryModel model) {
                      if (model.free) {
                        setState(() {
                          priceNumber = 'Free';
                          country = model.name;
                        });
                      } else if (availableCoins < model.price) {
                        Future.delayed(Duration(seconds: 1), () {
                          CnAppPopPageView.showCustomModalBottomSheet(
                              context,
                              const CnCoinStorePage(
                                isPodPage: true,
                              ));
                        });
                      } else {
                        setState(() {
                          priceNumber = '${model.price}';
                          country = model.name;
                        });
                      }
                    });
                  },
                  child: Container(
                    margin: EdgeInsets.only(left: 16),
                    height: 30,
                    decoration: BoxDecoration(
                        image: DecorationImage(
                            image: AssetImage('images/icon_coin_bg_mine.png'),
                            fit: BoxFit.fill)),
                    child: Row(
                      children: [
                        Container(
                          margin: EdgeInsets.only(left: 10),
                          child: Text(
                            '${country}',
                            style: TextStyle(
                                fontSize: 13, color: Color(0xFF404040)),
                          ),
                        ),
                        Container(
                          width: 19,
                          height: 17,
                          margin: EdgeInsets.only(left: 5),
                          child: Image.asset('images/icon_coins_logo_mine.png'),
                        ),
                        Container(
                          margin: EdgeInsets.only(left: 5),
                          child: Text('${priceNumber}',
                              style: TextStyle(
                                  fontSize: 13, color: Color(0xFFFF45A9))),
                        ),
                        Container(
                          width: 16,
                          height: 14,
                          margin: EdgeInsets.only(left: 5, right: 10),
                          child: Image.asset('images/icon_rightRow_mine.png'),
                        ),
                      ],
                    ),
                  ),
                ),
                InkWell(
                  onTap: () {
                    if (!CnClickUtils.isClick()) return;

                    CnAppPopPageView.showCustomModalBottomSheet(
                        context,
                        CnCoinStorePage(
                          isPodPage: true,
                        ));
                  },
                  child: Container(
                    margin: EdgeInsets.only(right: 16),
                    width: 76,
                    height: 30,
                    decoration: BoxDecoration(
                        image: DecorationImage(
                            image:
                                AssetImage('images/icon_mate_btn_bg_coin.png'),
                            fit: BoxFit.fill)),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Container(
                          width: 19,
                          height: 17,
                          margin: EdgeInsets.only(left: 5),
                          child: Image.asset('images/icon_coins_logo_mine.png'),
                        ),
                        Container(
                          margin: EdgeInsets.only(left: 5),
                          child: Text(
                            '${availableCoins}',
                            style: TextStyle(
                                fontSize: 13, color: Color(0xFF404040)),
                          ),
                        )
                      ],
                    ),
                  ),
                )
              ],
            ),
          ),
          Container(
            width: double.infinity,
            child: Stack(
              clipBehavior: Clip.none,
              children: [
                Container(
                  width: double.infinity,
                  height: 600,
                  child: const SVGASimpleImage(
                    assetsName: 'assets/before_matching.svga',
                  ),
                ),
                Positioned(
                    // bottom: 10,
                    // left: ((MediaQuery.of(context).size.width) - (215)) / 2,
                    child: Container(
                  child: Column(
                    children: [
                      InkWell(
                        onTap: () {
                          if (!CnClickUtils.isClick()) return;

                          _showRuletDialog(context, (isSure) {
                            if (priceNumber == 'Free') {
                              //发起匹配
                              Future.delayed(Duration(seconds: 1), () {
                                goToCnMateIngPage();
                              });

                              print('free');
                            } else if (availableCoins <
                                int.parse(priceNumber)) {
                              //发起匹配
                              Future.delayed(Duration(seconds: 1), () {
                                CnAppPopPageView.showCustomModalBottomSheet(
                                    context,
                                    const CnCoinStorePage(
                                      isPodPage: true,
                                    ));
                              });
                            } else {
                              //发起匹配
                              print('发起匹配,扣除金币接口');
                              _reviewModeConsumeData();
                            }
                          });
                        },
                        child: Container(
                            margin: EdgeInsets.only(
                                top: MediaQuery.of(context).size.height - 330),
                            alignment: Alignment.center,
                            width: 215,
                            height: 50,
                            decoration: const BoxDecoration(
                                image: DecorationImage(
                                    image: AssetImage(
                                        'images/icon_mate_btn_bg_start.png'),
                                    fit: BoxFit.fill)),
                            child: const Text(
                              'Tap to start',
                              style: TextStyle(
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold,
                                  color: Color(0xFFE71988)),
                            )),
                      ),
                      Container(
                        margin: EdgeInsets.only(top: 10),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Container(
                              width: 19,
                              height: 17,
                              margin: EdgeInsets.only(left: 5),
                              child: Image.asset(
                                  'images/icon_coins_logo_mine.png'),
                            ),
                            Container(
                              margin: EdgeInsets.only(left: 5),
                              child: Text(
                                '${priceNumber} coins each match',
                                style: TextStyle(
                                    fontSize: 14, color: Color(0xFF565656)),
                              ),
                            )
                          ],
                        ),
                      )
                    ],
                  ),
                )),
              ],
            ),
          )
        ],
      )),
    ));
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    event?.cancel();
  }

  @override
  void initState() {
    super.initState();
    loadJsonData();
    getCoins();

    event = EventBusUtils.getInstance()?.on().listen((event) {
      if (event.toString() == EventKeys.applePaySuccess) {
        getCoins();
      }
    });
  }

  Future<void> loadJsonData() async {
    String jsonString = await rootBundle.loadString('assets/area_conf.json');
    final jsonResponse = json.decode(jsonString);
    CnCountryListModel model = CnCountryListModel.coverFromJson(jsonResponse);
    setState(() {
      countryDataList = model.aboutMenu ?? [];
    });

    // 使用jsonResponse中的数据
    print(MediaQuery.of(context).size.width);
  }

//扣除金币接口
  _reviewModeConsumeData() {
    CnNetHelper.reviewModeConsumeData(9,
        (HDHResponseData configData, bool result, String msg) async {
      if (result) {
        CnNetHelper.getUserCoins().then((value) {
          setState(() {
            availableCoins = value;
          });
          goToCnMateIngPage();
        });
      } else {
        goToCnMateIngPage();
      }
    });
  }

  void goToCnMateIngPage() async {
    // final navigatorContext = Navigator.of(context);
    var userInfo = await Navigator.push(context,
        MaterialPageRoute(builder: (context) => const CnMateIngPage()));
    if (userInfo != null) {
      UserInfoModel? model = userInfo;

      Future.delayed(Duration(seconds: 1), () {
        _showResultDialog(context, userInfo, (isSure) {
          if (isSure == 'Agree') {
            CnNetHelper.channelGet(model?.userId ?? '',
                (HDHResponseData configData, bool result, String msg) {
              if (result) {
                Future.delayed(const Duration(seconds: 1), () {
                  CnChannelModel channelModel =
                      CnChannelModel.coverFromJson(configData.data);
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => CnCallingPage(
                                channelModel,
                                userId: userInfo.userId,
                                userData: model,
                              )));
                });
              } else {
                ToastUtils.show(configData.msg.toString());
              }
            });
          } else {
            Future.delayed(Duration(seconds: 1), () {
              goToCnMateIngPage();
            });
          }
        });
        Future.delayed(Duration(seconds: 1), () {
          ToastUtils.show('The other party has accepted this communication.');
        });
      });
    }
  }

  void getCoins() async {
    CnNetHelper.getUserCoins().then((value) {
      setState(() {
        availableCoins = value;
      });
    });
  }
}

//弹窗
typedef FunctionModelFun<String> = void Function(CnCountryModel model);
void _showCustomDialog(context, List<CnCountryModel> countryDataList,
    FunctionModelFun<String> backBlock) async {
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        backgroundColor: Color(0xFFDACED8),
        shape: const RoundedRectangleBorder(
          side: BorderSide(color: Color(0xCC50082F), width: 3.0), // 设置边框颜色和宽度
        ),
        contentPadding: const EdgeInsets.all(0),
        content: Container(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              // const SizedBox(height: 10),
              Container(
                color: Color(0xFFF7DFEC),
                width: double.infinity,
                height: 44,
                alignment: Alignment.center,
                child: const Text(
                  'Filter',
                  style: TextStyle(fontSize: 18, color: Colors.white),
                ),
              ),

              Container(
                  width: 300,
                  height: 300,
                  child: ListView.builder(
                      itemCount: countryDataList.length,
                      scrollDirection: Axis.vertical,
                      itemBuilder: (context, index) {
                        CnCountryModel model = countryDataList[index];
                        return InkWell(
                          onTap: () {
                            backBlock(model);
                            Navigator.of(context).pop();
                          },
                          child: Container(
                            height: 50,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Container(
                                  margin: EdgeInsets.only(left: 30),
                                  child: Row(
                                    children: [
                                      Container(
                                        width: 19,
                                        height: 17,
                                        margin: EdgeInsets.only(left: 5),
                                        child: model.free
                                            ? null
                                            : Image.asset(
                                                'images/icon_coins_logo_mine.png'),
                                      ),
                                      Container(
                                        margin: EdgeInsets.only(left: 5),
                                        child: Text(
                                          '${model.free ? 'Free' : model.price}',
                                          style: TextStyle(
                                              fontSize: 14,
                                              color: Color(0xFFFFFFFF)),
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                                Container(
                                  margin: EdgeInsets.only(right: 30),
                                  child: Text(
                                    '${model.name}',
                                    style: TextStyle(
                                        fontSize: 16, color: Color(0xFFFFFFFF)),
                                  ),
                                )
                              ],
                            ),
                          ),
                        );
                      })),
              const SizedBox(height: 20),
            ],
          ),
        ),
      );
    },
  );
}

typedef FunctionTest<String> = void Function(String isSure);
//字符串截取
String getSubString({required int end, required String str}) {
  if (str.length > end) {
    return "${str.substring(0, end)}...";
  } else {
    return str;
  }
}

//弹窗
void _showResultDialog(
    context, UserInfoModel userModel, FunctionTest<String> backBlock) {
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        backgroundColor: Color(0xFFDACED8),
        shape: RoundedRectangleBorder(
          // borderRadius: BorderRadius.circular(10.0), // 设置边框半径
          side: BorderSide(color: Color(0xCC50082F), width: 3.0), // 设置边框颜色和宽度
        ),
        contentPadding:
            const EdgeInsets.only(top: 10, left: 10, right: 10, bottom: 10),
        content: Container(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  InkWell(
                    onTap: () {
                      //更多弹窗
                      CnAnchorViewModel.getInfo()
                          .showMoreDialog(context, userModel, (value) {
                        //关注、取消关注
                        if (value == 'follow') {
                          userModel.isFollow = true;
                        } else if (value == 'followed') {
                          userModel.isFollow = false;
                        }
                        CnEventBus.instance!.commit(
                                                    EventKeys
                                                        .FollowListPageMessage,
                                                    null);
                      });
                    },
                    child: Container(
                      margin: EdgeInsets.only(right: 10, bottom: 5),
                      width: 30,
                      height: 30,
                      child: Image.asset('images/icon_more_btn.png'),
                    ),
                  ),
                ],
              ),
              Container(
                width: 300,
                height: 248,
                child: Image.network(
                  userModel.avatarUrl ?? '',
                  fit: BoxFit.fill,
                ),
              ),
              Row(
                children: [
                  Container(
                    margin: EdgeInsets.only(top: 16, left: 10),
                    child: Text(
                      '${getSubString(end: 8, str: userModel.nickname ?? "")}',
                      style: TextStyle(
                          color: Color(0xFF7F226B),
                          fontSize: 20,
                          fontWeight: FontWeight.bold),
                    ),
                  ),
                ],
              ),
              SizedBox(
                height: 10,
              ),
              Row(
                children: [
                  SizedBox(
                    width: 10,
                  ),
                  Text('${userModel.country}',
                      style: TextStyle(color: Color(0xFF134C8E), fontSize: 14)),
                  SizedBox(
                    width: 10,
                  ),
                  Text('${userModel.age}',
                      style: TextStyle(color: Color(0xFF980CA5), fontSize: 14)),
                ],
              ),
              InkWell(
                onTap: () {
                  backBlock('Agree');
                  Navigator.of(context).pop();
                },
                child: Container(
                    margin: EdgeInsets.only(top: 22),
                    width: 252,
                    height: 50,
                    alignment: Alignment.center,
                    decoration: const BoxDecoration(
                        image: DecorationImage(
                            image: AssetImage('images/icon_coin_bg_mine.png'))),
                    child: Container(
                      child: Text(
                        'Accept',
                        style:
                            TextStyle(fontSize: 18, color: Color(0xFFE71988)),
                      ),
                    )),
              ),
              InkWell(
                onTap: () {
                  backBlock('cancel');
                  Navigator.of(context).pop();
                },
                child: Container(
                    margin: EdgeInsets.only(top: 10),
                    alignment: Alignment.center,
                    height: 30,
                    child: Container(
                      // margin: EdgeInsets.only(left: 5),
                      child: Text(
                        'Next',
                        style: TextStyle(
                            color: Color(0x80000000),
                            fontSize: 14,
                            decoration: TextDecoration.underline,
                            decorationColor: Color(0x80000000),
                            decorationStyle: TextDecorationStyle.solid),
                        textAlign: TextAlign.center,
                      ),
                    )),
              ),
            ],
          ),
        ),
      );
    },
  );
}

//规则弹窗
void _showRuletDialog(context, FunctionTest<String> backBlock) {
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        backgroundColor: Color(0xFFDACED8),
        shape: RoundedRectangleBorder(
          // borderRadius: BorderRadius.circular(10.0), // 设置边框半径
          side: BorderSide(color: Color(0xCC50082F), width: 3.0), // 设置边框颜色和宽度
        ),
        contentPadding:
            const EdgeInsets.only(top: 20, left: 10, right: 10, bottom: 30),
        content: Container(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Container(
                margin: EdgeInsets.only(top: 16),
                child: Text(
                  'Regulations',
                  style: TextStyle(
                      color: Color(0xFFE71988),
                      fontSize: 20,
                      fontWeight: FontWeight.bold),
                ),
              ),
              const SizedBox(height: 16),
              const Text(
                  '1. In order to ensure a healthy environment in our app, please use polite language andprohibit abusive behavior during the call.',
                  style: TextStyle(color: Color(0x80000000), fontSize: 14)),
              const SizedBox(height: 5),
              const Text(
                  '2. You have the right to block other users who bring you bad experience, you will not see them again after blocked.',
                  style: TextStyle(color: Color(0x80000000), fontSize: 14)),
              const SizedBox(height: 5),
              const Text(
                  '3. You have the right to report other users who have a negative influence, we will inform and deal with the reported user within 24hours.',
                  style: TextStyle(color: Color(0x80000000), fontSize: 14)),
              const SizedBox(height: 5),
              const Text(
                  '4. During the Tap to start process, bothparties need to agree to each other in orderto chat.',
                  style: TextStyle(color: Color(0x80000000), fontSize: 14)),
              InkWell(
                onTap: () {
                  backBlock('Agree');
                  Navigator.of(context).pop();
                },
                child: Container(
                    margin: EdgeInsets.only(top: 30),
                    width: 252,
                    height: 50,
                    alignment: Alignment.center,
                    decoration: const BoxDecoration(
                        image: DecorationImage(
                            image: AssetImage('images/icon_coin_bg_mine.png'))),
                    child: Container(
                      child: Text(
                        'OK',
                        style:
                            TextStyle(fontSize: 18, color: Color(0xFFE71988)),
                      ),
                    )),
              ),
            ],
          ),
        ),
      );
    },
  );
}
